package com.atguigu.springcloud.feign;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 权限线程变量
 * @date 2021/10/14 11:01
 */
public class AuthThreadLocal {

    protected static final String AUTHORIZATTON = "Authorization";

    //多线程访问同一个共享变量的时候容易出现并发问题，特别是多个线程对一个变量进行写入的时候，
    // 为了保证线程安全，一般使用者在访问共享变量的时候需要进行额外的同步措施才能保证线程安全性。
    //ThreadLocal对象每次set值都不会覆盖，而且是单独独立的
    private final static ThreadLocal<Map<String, String>> auth = new ThreadLocal<Map<String, String>>();

    protected final static String G_AUTH = "g-auth";


    /**
     * @description: 设置
     */
    public static void set(Map<String, String> map) {
        auth.set(map);
    }

    /**
     * @description: 获取
     */
    public static Map<String, String> get() {
        return auth.get();
    }

    /**
     * @description: 移除
     */
    public static void remove() {
        auth.remove();
    }

    /**
     * @description: 获取map
     */
    public static Map<String, String> getRequestMap() {
        HttpServletRequest request = null;
        String gAuth = null;
        String authorization = null;
        //取得当前线程下的Request、Session的Attribute值,获取当前请求的线程拿到请求request获取头信息
        try {
            request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            gAuth = request.getHeader(G_AUTH);
            authorization = request.getHeader(AUTHORIZATTON);
        } catch (IllegalStateException e) {
            gAuth = "admin&admin&ROOT";
            authorization = "ScheduIed" + UUID.randomUUID().toString();
        }
        Map<String, String> map = new HashMap<>(2);
        map.put(G_AUTH, gAuth);
        map.put(AUTHORIZATTON, authorization);
        return map;
    }

}
